﻿<%@ WebHandler Language="C#" Class="CheckPointQRCodeVue3PageHandler" %>

/* Description:实测值录入二维码
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2024.8.29
 */

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Configuration;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using NPOI.SS.UserModel;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections;

public class CheckPointQRCodeVue3PageHandler : IHttpHandler
{
    public class MDM_Product
    {
        public string PN { get; set; }//零件号
        public string[] BN { get; set; }//批次号列表
        public List<MDM_Process> Cts { get; set; }//内容
    }

    //工序
    public class MDM_Process
    {
        public string PN { get; set; }//工序号
        public int Qty { get; set; }//特征数量 PS:这个工序一共有多少个特征
        public List<MDM_TestItem> Its { get; set; }//特征项
    }

    //特征项
    public class MDM_TestItem
    {
        public string BN { get; set; }//气泡号
        public string UM { get; set; }//单向标识
        public string LowVal { get; set; }//下公差
        public string NomVal { get; set; }//理论值
        public string UppVal { get; set; }//上公差
    }

    public class MDM_Task
    {
        public string PN { get; set; }//零件号
        public string No { get; set; }
        public List<MDM_Sample> Sps { get; set; }//工序号
    }

    public class MDM_Sample
    {
        public string BN { get; set; }//样品号
        public List<MDM_Inspect> Ins { get; set; }//测量值
    }

    public class MDM_Inspect
    {
        public string BN { get; set; }//气泡号
        public string SPNO { get; set; }//工序号
        public string MeaVal { get; set; }//测量值
    }

    class QRCode
    {
        public QRCode(string image, string containername)
        {
            this.image = image;
            this.containername = containername;
        }
        public string image { get; set; }
        public string containername { get; set; }//工序号
    }
    public bool IsReusable { get { return false; } }
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness m_CommonObj = new uLMSCommonBusiness();
    uLMSCommonIBusiness m_Common = uMESBusinessFactory.instance.GetuLMSCommonObject();
    uLMSStepCheckPointIBusiness m_CheckPointObj = uMESBusinessFactory.instance.GetuLMSStepCheckPointObject();
    string usingImg = ConfigurationManager.AppSettings["UsingCheckImageSavePath"];
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (System.IO.StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                uMESProcessResult r = new uMESProcessResult();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getContainerQRCode"://生成二维码
                        r = getContainerQRCode(jObject, context);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "saveQRCode":
                        r = saveQRCode(jObject, context);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "generateQRCodeString":
                        r = generateQRCodeString(jObject);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                uMESProcessResult r = new uMESProcessResult() { ReturnData = null, RowCount = "0", Code = "500", Message = e.Message };
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    uMESProcessResult saveQRCode(JObject obj, HttpContext context)
    {
        string containerStepWorkReportID = obj["containerStepWorkReportID"].ToString();//报工ID
        string type = obj["saveType"].ToString();//1:报工；2：检验
        CurrentUserInfo m_UserInfo = m_Common.GetUserInfo(obj["employeename"].ToString(), "");
        DataTable dtt = JsonConvert.DeserializeObject<DataTable>(obj["postData"].ToString());

        var selectSQL = @"SELECT c2.MFGWORKFLOWID,w.WORKFLOWSTEPNAME,c2.CONTAINERID,c.CONTAINERID CHILDCONTAINERID,s.SPECNO,st.BUBBLENUMBER,st.STEPCHECKPOINTID,str.stepcheckpointresultid,csw.containerstepworkreportid FROM CONTAINER c 
                     LEFT JOIN CONTAINER c2 ON c2.CONTAINERID =c.PARENTCONTAINERID 
                     LEFT JOIN WORKFLOWSTEP w ON w.WORKFLOWID =c2.MFGWORKFLOWID 
                     left join containerstepworkreport csw on csw.containerid =c.PARENTCONTAINERID and csw.isuse =0
                     LEFT JOIN specbase sp ON sp.specbaseid=w.specbaseid
	                 LEFT JOIN spec s ON s.specbaseid=sp.specbaseid OR s.specid=w.specid
	                 LEFT JOIN STEPCHECKPOINT st ON st.WORKFLOWSTEPID =w.WORKFLOWSTEPID
	                 LEFT JOIN STEPCHECKPOINTRESULT str ON str.STEPCHECKPOINTID =st.STEPCHECKPOINTID AND str.CONTAINERID =c2.CONTAINERID AND str.CHILDCONTAINERID =c.CONTAINERID 
                     WHERE c.CONTAINERNAME ='{0}' AND   s.SPECNO='{1}' and st.BUBBLENUMBER='{2}'
                     UNION 
                    SELECT NULL MFGWORKFLOWID,w.WORKFLOWSTEPNAME,c.CONTAINERID,'' CHILDCONTAINERID,s.SPECNO,st.BUBBLENUMBER,st.STEPCHECKPOINTID,str.stepcheckpointresultid,csw.containerstepworkreportid FROM CONTAINERCURRENTINFO c 
                     LEFT JOIN WORKFLOWSTEP w ON w.WORKFLOWID =DECODE(c.isinstore,1,c.bsworkflowid,c.workflowid) 
                     left join containerstepworkreport csw on csw.containerid =c.containerid and csw.isuse =0 and csw.workflowstepid =w.workflowstepid
                     LEFT JOIN specbase sp ON sp.specbaseid=w.specbaseid
	                 LEFT JOIN spec s ON s.specbaseid=sp.specbaseid OR s.specid=w.specid
	                 LEFT JOIN STEPCHECKPOINT st ON st.WORKFLOWSTEPID =w.WORKFLOWSTEPID
	                 LEFT JOIN STEPCHECKPOINTRESULT str ON str.STEPCHECKPOINTID =st.STEPCHECKPOINTID AND str.CONTAINERID =c.CONTAINERID 
                     WHERE c.CONTAINERNAME ='{0}' AND   s.SPECNO='{1}' and st.BUBBLENUMBER='{2}'";
        var insertSQL = @"INSERT INTO STEPCHECKPOINTRESULT (lastchangedate,tempdealfail,CHECKERID,CHECKPOINTRESULTNOTE,CHECKPOINTRESULTNOTEDIS,CONTAINERID,CHECKDATE,FACTORYID,STEPCHECKPOINTID,STEPCHECKPOINTRESULTID,containerstepworkreportid,NOTES,CHILDCONTAINERID) 
                                VALUES(sysdate,0,'{0}','{1}','{2}','{3}',sysdate,'{4}','{5}',sys_guid(),'{6}','{7}','{8}')";
        var updateSql = @"UPDATE STEPCHECKPOINTRESULT SET lastchangedate=sysdate,tempdealfail=0,CHECKPOINTRESULTNOTE='{0}',CHECKPOINTRESULTNOTEDIS='{1}',CheckerID='{2}',checkdate=sysdate,ContainerStepWorkReportID='{3}',checkresultdocpath='{4}' where STEPCHECKPOINTRESULTID='{5}'";

        if ("1".Equals(type))//报工实测值录入
        {
            insertSQL = @"INSERT INTO STEPCHECKPOINTRESULT (lastchangedate,tempdealfail,WORKERID,WORKCHECKPOINTRESULTNOTE,WORKCHECKPOINTRESULTNOTEDIS,CONTAINERID,CREATEDATE,FACTORYID,STEPCHECKPOINTID,STEPCHECKPOINTRESULTID,containerstepworkreportid,NOTES,CHILDCONTAINERID) 
                                VALUES(sysdate,0,'{0}','{1}','{2}','{3}',sysdate,'{4}','{5}',sys_guid(),'{6}','{7}','{8}')";
            updateSql = @"UPDATE STEPCHECKPOINTRESULT SET lastchangedate=sysdate,tempdealfail=0,WORKCHECKPOINTRESULTNOTE='{0}',WORKCHECKPOINTRESULTNOTEDIS='{1}',WORKERID='{2}',checkdate=sysdate,ContainerStepWorkReportID='{3}',checkresultdocpath='{4}' where STEPCHECKPOINTRESULTID='{5}'";
        }

        var arryList = new ArrayList();
        foreach (DataRow dr in dtt.Rows)
        {
            try
            {
                string DecBase64 = System.Net.WebUtility.HtmlEncode(dr["checkresult"].ToString());
                string DecJson = DecompressString(DecBase64);
                var Task = JsonConvert.DeserializeObject<MDM_Task>(DecJson);
                var json = JsonConvert.SerializeObject(Task);

                var productName = Task.PN;//零件号
                foreach (MDM_Sample sam in Task.Sps)
                {
                    var childComtainer = sam.BN;//子批次号
                    foreach (MDM_Inspect ins in sam.Ins)
                    {
                        var bubblenumber = ins.BN;//气泡号
                        var meaVal = ins.MeaVal;//实测值
                        var spno = Task.No;//工序号\
                        string sql = string.Format(selectSQL, productName + "/" + childComtainer, spno, bubblenumber);
                        DataTable scrDT = DatabaseHelper.Query_ReturnDatTable(sql);
                        if (scrDT.Rows.Count == 0) { continue; }
                        DataRow drow = scrDT.Rows[0];
                        if (string.IsNullOrWhiteSpace(drow["STEPCHECKPOINTRESULTID"].ToString()))
                        {
                            arryList.Add(string.Format(
                                insertSQL,
                                m_UserInfo.EmployeeID,
                                meaVal,
                                m_CheckPointObj.
                                ConvertTohtml(meaVal, usingImg, false),
                                drow["CONTAINERID"],
                                m_UserInfo.FactoryID,
                                drow["STEPCHECKPOINTID"],
                                drow["containerstepworkreportid"],
                                "二维码导入",
                                drow["CHILDCONTAINERID"]));
                        }
                        else
                        {
                            arryList.Add(string.Format(
                                updateSql,
                                meaVal,
                                m_CheckPointObj.ConvertTohtml(meaVal, usingImg, false),
                                m_UserInfo.EmployeeID,
                                drow["containerstepworkreportid"],
                                "",
                                drow["STEPCHECKPOINTRESULTID"].ToString()));
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                return new uMESProcessResult() { ReturnData = false, RowCount = "0", Code = "200", Message = "二维码解析报错：" + ex.Message };
            }
        }
        if (arryList.Count > 0)
        {
            bool isSuccess = DatabaseHelper.ExecuteSqlListTran(arryList);
            return new uMESProcessResult() { ReturnData = isSuccess, RowCount = "0", Code = "200", Message = isSuccess ? "数据提交成功" : "数据提交失败" };
        }
        else
        {
            return new uMESProcessResult() { ReturnData = false, RowCount = "0", Code = "200", Message = "数据提交失败" };
        }
    }

    uMESProcessResult getContainerQRCode(JObject obj, HttpContext context)
    {
        var containernames = obj["containernames"].ToString();
        var childContainers = obj["childContainers"].ToString();
        var checkPoints = obj["checkPoints"].ToString();
        var mDT = getContainerData(containernames, childContainers);
        var realcontainerno = string.Empty;
        if (string.IsNullOrWhiteSpace(childContainers))
        {
            foreach (DataRow dr in mDT.Rows)
            {
                realcontainerno += dr["realcontainerno"].ToString() + ",";
            }
            mDT = mDT.Select("containername='" + mDT.Rows[0]["containername"] + "'").CopyToDataTable();
        }

        var InnerHtml = string.Empty;
        List<QRCode> list = new List<QRCode>();
        if (mDT.Rows.Count > 0)
        {
            for (var j = 0; j < mDT.Rows.Count; j++)
            {
                DataRow row = mDT.Rows[j];
                var ddt = getStepCheckPoint(row["containerName"].ToString(), checkPoints);
                if (ddt.Rows.Count > 0)
                {
                    var childContainerNo = string.IsNullOrWhiteSpace(row["childContainerNo"].ToString()) ? realcontainerno.TrimEnd(',') : row["childContainerNo"].ToString();
                    var contentData = getProductJson2(row["productname"].ToString(), childContainerNo, ddt);
                    for (var i = 0; i < contentData.Split(';').Length; i++)
                    {
                        var content = contentData.Split(';')[i].ToString();

                        if (!string.IsNullOrWhiteSpace(contentData))
                        {
                            ////string.Format("data:image/Jpeg;base64,{0}", CreateQRCodeImg(xml));
                            var ImageUrl = "/InSiteWebApplication/qrcodeimgs/" + CreateQRCodeImg(content, context);
                            var containerBM = contentData.Split(';').Length > 1 ? "(" + (i + 1) + ")" : "";
                            list.Add(new QRCode(ImageUrl, row["containerName"].ToString() + containerBM));
                        }
                    }
                }
                else
                {
                    return new uMESProcessResult() { ReturnData = false, RowCount = "0", Code = "200", Message = "查询批次号没有维护检测项信息" };
                }
            }
            return new uMESProcessResult() { ReturnData = list, RowCount = "0", Code = "200", Message = "请求成功" };
        }
        else
        {
            return new uMESProcessResult() { ReturnData = false, RowCount = "0", Code = "200", Message = "没有查询到相关批次号信息" };
        }
    }

    //生成检测结果字符串（测试用）
    uMESProcessResult generateQRCodeString(JObject obj)
    {
        string productname = obj["productname"].ToString();
        string specno = obj["specno"].ToString();
        string togetherflag = obj["togetherflag"].ToString();

        var task = new MDM_Task()
        {
            PN = productname,
            No = specno,
            Sps = new List<MDM_Sample>()
            {
                new MDM_Sample(){
                    BN = togetherflag,
                    Ins = new List<MDM_Inspect>() { 
                        new MDM_Inspect(){BN="1", SPNO = togetherflag,MeaVal = Guid.NewGuid().ToString()}
                    }
                }
            }
        };
        var t = System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(task)));
        return new uMESProcessResult() { ReturnData = t, RowCount = "0", Code = "200", Message = "请求成功" };
    }

    private DataTable getContainerData(string containerName, string childContainers)
    {
        var sqlStr = @"SELECT con.containername,con.realcontainerno,con.productname,a.childContainerNo
       FROM containercurrentinfo con 
       LEFT JOIN ( 
       	SELECT wm_concat(SUBSTR(c.CONTAINERNAME,INSTR(c.CONTAINERNAME,'/')+1)) childContainerNo,c.PARENTCONTAINERID 
       	FROM CONTAINER c WHERE c.CONTAINERID IN('{0}') 
       	GROUP by c.PARENTCONTAINERID 
       ) a ON a.PARENTCONTAINERID=con.CONTAINERID 
       WHERE containername in('{1}')";
        return DatabaseHelper.Query_ReturnDatTable(string.Format(sqlStr, childContainers.Replace(",", "','"), containerName.Replace(",", "','")));
    }

    private DataTable getStepCheckPoint(string containerName, string checkpintids)
    {
        var sqlStr = @"SELECT con.containername,con.realcontainerno,con.productname,con.productrevision,con.workflowname,con.workflowrevision,s.specno,
ws.workflowstepid,ws.workflowstepname,st.checkno,
st.bubblenumber,st.floorfloat,st.basevalue,st.ceilfloat,st.singlesign,
s.specno||'$'||st.bubblenumber||'#'||REPLACE(st.floorfloat,'+','')||'|'||st.basevalue||'|'||REPLACE(st.ceilfloat,'-','') sdata
FROM containercurrentinfo con 
LEFT JOIN workflowstep ws ON ws.workflowid=DECODE(con.isinstore,1,con.bsworkflowid,con.workflowid)
LEFT JOIN specbase sp ON sp.specbaseid=ws.specbaseid
LEFT JOIN spec s ON s.specbaseid=sp.specbaseid OR s.specid=ws.specid
LEFT JOIN stepcheckpoint st ON st.workflowstepid=ws.workflowstepid
WHERE st.stepcheckpointid IS NOT NULL AND con.containername IN('{0}')
and st.stepcheckpointid in ('{1}')
ORDER BY s.specno,st.bubblenumber";
        sqlStr = string.Format(sqlStr, containerName.Replace(",", "','"), checkpintids.Replace(",", "','"));
        return DatabaseHelper.Query_ReturnDatTable(sqlStr);
    }

    protected string CreateQRCodeImg(string str, HttpContext context)
    {
        QRCoder.QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();

        QRCoder.QRCodeData qrCodeData = qrGenerator.CreateQrCode(str, QRCoder.QRCodeGenerator.ECCLevel.L);
        QRCoder.QRCode qrcode = new QRCoder.QRCode(qrCodeData);

        Bitmap qrCodeImage = qrcode.GetGraphic(6, Color.Black, Color.White, null, 5, 1, false);
        MemoryStream ms = new MemoryStream();
        var savePath = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
        //(@"C:\Program Files (x86)\Camstar\InSite Web Application\InSiteWebApplication\qrcodeimgs\123.jpg");
        qrCodeImage.Save(context.Server.MapPath("~/qrcodeimgs/" + savePath));
        ms.Close();

        DirectoryInfo directory = new DirectoryInfo(context.Server.MapPath("~/qrcodeimgs/"));
        FileInfo[] files = directory.GetFiles("*.jpg");
        var targetDate = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
        foreach (var file in files)
        {
            if (file.CreationTime.ToString("yyyyMMdd") == targetDate || file.LastWriteTime.ToString("yyyyMMdd") == targetDate)
            {
                file.Delete();
            }
        }

        return savePath;
    }

    //零件号，批次号列表，检测项
    public string getProductJson(string PN, string BN, DataTable checkDT)
    {
        var pList = new List<MDM_Product>();
        var product = new MDM_Product();
        product.PN = PN;//零件号
        product.BN = BN.Split(',');//批次号列表
        List<MDM_Process> Cts = new List<MDM_Process>();

        List<MDM_TestItem> Its = new List<MDM_TestItem>();
        var index = 0;
        var specno = checkDT.Rows[0]["specno"].ToString();
        var content = string.Empty;
        foreach (DataRow dr in checkDT.Rows)
        {
            if (!specno.Equals(dr["specno"].ToString()))
            {

                MDM_Process ct = new MDM_Process();
                ct.Its = Its;
                ct.Qty = Its.Count;
                ct.PN = specno;
                Cts = new List<MDM_Process>();
                Cts.Add(ct);
                specno = dr["specno"].ToString();

                //第二道工序--到最后一道工序(第一个检测项)的逻辑
                Its = new List<MDM_TestItem>();
                MDM_TestItem it = new MDM_TestItem();//
                it.BN = dr["bubblenumber"].ToString();//气泡号
                it.UM = dr["singlesign"].ToString();//单向标识
                it.LowVal = dr["ceilfloat"].ToString();//下公差
                it.NomVal = dr["basevalue"].ToString();//理论值
                it.UppVal = dr["floorfloat"].ToString();//上公差
                Its.Add(it);
                if (!isMaxlength(product, Cts))//判断是否超出了最大长度
                {
                    product.Cts = Cts;
                    var ComUrl = System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(product)));
                    content += ComUrl + ";";
                    pList.Add(getProduct(ComUrl));
                    Cts = new List<MDM_Process>();
                    product.Cts = Cts;
                }
            }
            else
            {

                //第一道工序的所有逻辑、开始第二个往后检测项的逻辑
                MDM_TestItem it = new MDM_TestItem();
                it.BN = dr["bubblenumber"].ToString();//气泡号
                it.UM = dr["singlesign"].ToString();//单向标识
                it.LowVal = dr["ceilfloat"].ToString();//下公差
                it.NomVal = dr["basevalue"].ToString();//理论值
                it.UppVal = dr["floorfloat"].ToString();//上公差
                Its.Add(it);

                if (specno.Equals(dr["specno"].ToString()) && Cts.Count == 0)
                {
                    MDM_Process ct = new MDM_Process();
                    ct.Its = Its;
                    ct.Qty = Its.Count;
                    ct.PN = specno;
                    Cts = new List<MDM_Process>();
                    Cts.Add(ct);
                }

                if (!isMaxlength(product, Cts))
                {
                    product.Cts = Cts;
                    var ComUrl = System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(product)));
                    content += ComUrl + ";";
                    pList.Add(getProduct(ComUrl));
                    Cts = new List<MDM_Process>();
                    Its = new List<MDM_TestItem>();
                    product.Cts = Cts;
                }
            }
            index++;
            //最后一道工序，最后一个检测项的逻辑
            if (index == checkDT.Rows.Count)
            {
                MDM_Process ct = new MDM_Process();
                ct.Its = Its;
                ct.Qty = Its.Count;
                ct.PN = specno;
                Cts.Add(ct);
                product.Cts = Cts;
                var ComUrl = System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(product)));
                content += ComUrl + ";";
                pList.Add(getProduct(ComUrl));
                Cts = new List<MDM_Process>();
                Its = new List<MDM_TestItem>();
                product.Cts = Cts;
            }
        }

        var JP = JsonConvert.SerializeObject(pList);

        for (var j = 0; j < content.TrimEnd(';').Split(';').Length; j++)
        {
            string DecBase64 = System.Net.WebUtility.HtmlEncode(content.Split(';')[j]);
            string DecJson = DecompressString(DecBase64);
        }


        var json = Newtonsoft.Json.JsonConvert.SerializeObject(product);

        return content.TrimEnd(';');
    }

    public string getProductJson2(string PN, string BN, DataTable checkDT)
    {
        var pList = new List<MDM_Product>();
        var product = new MDM_Product { PN = PN, BN = BN.Split(',') };
        List<MDM_Process> Cts = new List<MDM_Process>();
        List<MDM_TestItem> Its = new List<MDM_TestItem>();
        string specno = checkDT.Rows[0]["specno"].ToString();

        foreach (DataRow dr in checkDT.Rows)
        {
            if (!specno.Equals(dr["specno"].ToString()))
            {
                MDM_Process ct = new MDM_Process { Its = Its, Qty = Its.Count, PN = specno };
                Cts.Add(ct);
                specno = dr["specno"].ToString();

                Its = new List<MDM_TestItem> { new MDM_TestItem
            {
                BN = dr["bubblenumber"].ToString(),
                UM = dr["singlesign"].ToString(),
                LowVal = dr["ceilfloat"].ToString(),
                NomVal = dr["basevalue"].ToString(),
                UppVal = dr["floorfloat"].ToString()
            } };
            }
            else
            {
                Its.Add(new MDM_TestItem
                {
                    BN = dr["bubblenumber"].ToString(),
                    UM = dr["singlesign"].ToString(),
                    LowVal = dr["ceilfloat"].ToString(),
                    NomVal = dr["basevalue"].ToString(),
                    UppVal = dr["floorfloat"].ToString()
                });
            }

            if (checkDT.Rows.IndexOf(dr) == checkDT.Rows.Count - 1 || (checkDT.Rows.IndexOf(dr) + 1) % 100 == 0)
            {
                MDM_Process ct = new MDM_Process { Its = Its, Qty = Its.Count, PN = specno };
                Cts.Add(ct);
                product.Cts = Cts;
                var ComUrl = System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(product)));
                pList.Add(getProduct(ComUrl));
                Cts = new List<MDM_Process>();
                Its = new List<MDM_TestItem>();
            }
        }

        return string.Join(";", pList.Select(p => System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(p)))));
    }

    public Boolean isMaxlength(MDM_Product ProductKey, List<MDM_Process> cts)
    {

        ProductKey.Cts = cts;
        string json = JsonConvert.SerializeObject(ProductKey);
        string ComBase64 = CompressString(json);
        string ComUrl = System.Net.WebUtility.HtmlEncode(ComBase64);

        string DecBase64 = System.Net.WebUtility.HtmlEncode(ComUrl);
        string DecJson = DecompressString(DecBase64);
        var GitKey = JsonConvert.DeserializeObject<MDM_Product>(DecJson);

        return ComUrl.Length < 200;
    }

    public MDM_Product getProduct(string ComUrl)
    {
        string DecBase64 = System.Net.WebUtility.HtmlEncode(ComUrl);
        string DecJson = DecompressString(DecBase64);
        var GitKey = JsonConvert.DeserializeObject<MDM_Product>(DecJson);
        return GitKey;
    }

    public static string CompressString(string text)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(text);

        using (MemoryStream ms = new MemoryStream())
        {
            using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true))
            {
                gzip.Write(buffer, 0, buffer.Length);
            }

            byte[] compressed = ms.ToArray();
            return Convert.ToBase64String(compressed);
        }
    }

    public static string DecompressString(string compressedBase64)
    {
        byte[] compressed = Convert.FromBase64String(compressedBase64);

        using (MemoryStream ms = new MemoryStream(compressed))
        {
            using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress))
            {
                using (StreamReader reader = new StreamReader(gzip, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}